package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbDict;
import com.bwie.service.TbDictService;
import com.bwie.mapper.TbDictMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
* @author Lenovo
* @description 针对表【tb_dict(字典表)】的数据库操作Service实现
* @createDate 2025-03-25 21:55:07
*/
@Service
public class TbDictServiceImpl extends ServiceImpl<TbDictMapper, TbDict>
    implements TbDictService{

    @Autowired
    private TbDictMapper tbDictMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 项目启动时，从数据库中读取字典数据，到缓存中
     */
//    @PostConstruct
//    public void loadDict(){
//        System.out.println("加载字典数据到缓存中");
//        List<TbDict> tbDicts = tbDictMapper.selectList(null);
//
//        String key = "dict";
//        for (TbDict tbDict : tbDicts) {
//            Boolean hasKey = redisTemplate.opsForHash().hasKey(key, tbDict.getDictId().toString());
//            if(!hasKey){
//                redisTemplate.opsForHash().put(key,tbDict.getDictId().toString(),JSON.toJSONString(tbDict));
//            }
//        }
////        List<TbDict> tbDicts = tbDictMapper.selectList(null);
////        redisTemplate.opsForValue().set("dict", JSON.toJSONString(tbDicts));
//    }

    @PostConstruct
    public void loadDict(){
        System.out.println("加载字典表数据到缓存中");

        List<TbDict> tbDicts = tbDictMapper.selectList(null);

        String key = "dict";
        //增量更新
        for (TbDict tbDict : tbDicts) {
            Boolean aBoolean = redisTemplate.opsForHash().hasKey(key, tbDict.getDictId().toString());
            if(!aBoolean){
                redisTemplate.opsForHash().put(key,tbDict.getDictId().toString(),JSON.toJSONString(tbDict));
            }
        }
    }

}




